

import getopt
import os.path
import string
import subprocess
import sys
import tokenize
import traceback

from ConfigParser import SafeConfigParser
from Configurable import *
from Daemon import *
from Util import *
from Setup import *

class Testcloud (Configurable):
    
    def __init__(self, conf):
        Configurable.__init__(self, conf)

    def start(self):
        output = shell_exec(self.config.get("testcloud", "daemon_check"))
        lines = output.split("\n")
        found_other = False
        counter = 0
        for line in lines:
            if  line != "" and line.find("Testcloud.py") >= 0:
                counter += 1
                if counter > 1:
                    found_other = True
                    break  
        
        #tuples = output.split(" ")
        #if os.path.exists(pid_path) and read_as_string(pid_path) is not None:
        if  not found_other:
            daemon = Daemon(self.config_file)
            daemon.run() 
        else:
            print "There is already a Testcloud daemon running, aborting."
            sys.exit(2)
            #process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
            #output = process.stdout.read()
            #append_string(str(process.pid), pid_path)
    
    
    def stop(self):
        print "stop"
        
    def status(self):
        print "status"
        
    def setup(self):
        setup = Setup(self.config_file)
        setup.setup()

def usage():
    usage = "Usage: testcloud start|stop|status|setup"
    print usage

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "")
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    
    if len(args) < 1:
        usage()

    for arg in args:
        if arg in ["start", "stop", "status", "setup"]:
            try:
                testcloud = Testcloud("/etc/testcloud.cfg")
                eval("testcloud.%s()" % arg)
            except KeyboardInterrupt:
                sys.exit(0)
            except Exception, e:
                traceback.print_exc(file=sys.stdout)
                sys.exit(0)
        else:
            usage()
        
if __name__ == "__main__":
    main()

    
